package com.qdxwx.data.service.coupon;

import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.utils.ObjectUtils;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.mapper.coupon.CouponCodeMapper;
import com.qdxwx.data.service.course.CourseService;
import com.qdxwx.data.service.user.UserLetterService;
import com.qdxwx.models.coupon.Coupon;
import com.qdxwx.models.coupon.CouponCode;
import com.qdxwx.models.coupon.CouponCodeDTO;
import com.qdxwx.models.coupon.CouponCodeQuery;
import com.qdxwx.models.course.Course;
import com.qdxwx.models.enums.LetterTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CouponCodeServiceImpl implements CouponCodeService {

	private static final Logger logger = LoggerFactory.getLogger(CouponCodeServiceImpl.class);

	@Autowired
	private CouponCodeMapper couponCodeMapper;
	@Autowired
	private CouponService couponService;
	@Autowired
	private CourseService courseService;
	@Autowired
	private UserLetterService userLetterService;

	@Override
	public int insert(CouponCode couponCode) {
		couponCode.setCreateTime(LocalDateTime.now());
		return couponCodeMapper.insertCouponCode(couponCode);
	}

	@Override
	public void deleteById(Long id) {
		if (id > 0) {
			couponCodeMapper.deleteCouponCodeById(id);
		}
	}

	@Override
	public void deleteByCouponId(Long couponId) {
		if (couponId>0) {
			couponCodeMapper.deleteCouponCodeByCouponId(couponId);
		}
	}

	/*
	 * 修改CouponCode
	 */
	@Override
	public int update(CouponCode couponCode) {
		if(couponCode.getId() < 1) return 0;
		return couponCodeMapper.updateCouponCode(couponCode);
	}

	/*
	 * 指派优惠券给用户
	 */
	@Override
	public void updateUser(CouponCode couponCode) {
		if (couponCode.getUserId()>0 && couponCode.getId()>0) {
			couponCodeMapper.updateCouponCodeUser(couponCode);
		}
	}

	/*
	 * 根据id获取单个CouponCode对象
	 */
	@Override
	public CouponCode get(Long id) {
		if (id <= 0) return null;
		return couponCodeMapper.getCouponCodeById(id);
	}

	/*
	 * 根据优惠券编码获取单个CouponCode对象
	 */
	@Override
	public CouponCodeDTO getDTOByCode(String code) {
		if (TKString.isEmpty(code)) {
			return null;
		}
		return couponCodeMapper.getCouponCodeDTOByCode(code);
	}

	/*
	 * id查询优惠券编码
	 */
	@Override
	public CouponCodeDTO getDTO(Long id) {
		if (id < 0) {
			return null;
		}
		return couponCodeMapper.getCouponCodeDTOById(id);
	}

	/*
	 * 过期的优惠编码改状态
	 */
	@Override
	public void overdueCodeByTime() {
		try {
			couponCodeMapper.overdueCodeByTime();
			/*查询即将过去的优惠券信息*/
			List<CouponCodeDTO> couponCodeDTOs = couponCodeMapper.getCouponCodeDTOByTimeOver();
			for (CouponCodeDTO couponCodeDTO : couponCodeDTOs) {
				userLetterService.send(couponCodeDTO.getUserId(), LetterTemplate.COUPON_OVER, couponCodeDTO.getCouponCode());
			}

		} catch (Exception e) {
			logger.error("overdueCodeByTime is error", e);
		}
	}

	/*
	 * 优惠编码使用限制
	 */
	@Override
	public Map<String, Object> checkCode(CouponCodeDTO couponCodeDTO, List<Course> courses, Long userId) {
		String resultMsg = "";
		Map<String, Object> map = new HashMap<>();
		if (couponCodeDTO.getStatus() == 2) {
			resultMsg = "优惠券已使用";
		} else if (couponCodeDTO.getStatus() == 3) {
			resultMsg = "优惠券已过期";
		} else if (couponCodeDTO.getStatus() == 4) {
			resultMsg = "优惠券已作废";
		} else if (couponCodeDTO.getStartDate().isAfter(LocalDate.now())) {
			resultMsg = "优惠券不在使用期限内";
		} else if (ObjectUtils.isNotNull(userId) && !userId.equals(couponCodeDTO.getUserId())) {
			resultMsg = "优惠券已被占用";
		} else {
			LocalDate startDate = couponCodeDTO.getStartDate();
			LocalDate endDate = couponCodeDTO.getEndDate();
			LocalDate nowDate = LocalDate.now();
			if (nowDate.isBefore(startDate) || nowDate.isAfter(endDate)) {
				resultMsg = "优惠券不在使用期限内";
			}
		}
		if (!resultMsg.equals("")) {
			map.put("msg", resultMsg);
			return map;
		}

		Coupon coupon = couponService.get(couponCodeDTO.getCouponId());
		if (coupon.getTotalNum() != 0 && coupon.getTotalNum() <= coupon.getUseNum()) {
			map.put("msg", "优惠券使用次数受限");
			return map;
		}

		double tempPrice = 0.00;//临时价格
		StringBuilder courseIds = new StringBuilder();//购物车课程id字符串
		//所有课程都能用
		for (Course course : courses) {//购物车课程id字符串
			courseIds.append(course.getCourseId()).append(",");
		}
		//课程限制集合
		List<Course> limitCourses = couponService.getLimitCourseById(couponCodeDTO.getCouponId());

		//优惠券项目限制,含有该项目下的课程且含有课程总价格大于优惠券限制价格
		if (couponCodeDTO.getChannelId() > 0) {
			courseIds = new StringBuilder(courseIds.substring(0, courseIds.length() - 1));
			//购物车中满足项目限制的课程集合
			List<Course> subjectCourses = courseService.getCouponSubjectCourse(couponCodeDTO.getChannelId(), courseIds.toString());
			StringBuilder limitCourseIds = new StringBuilder();//记录优惠的课程id字符串，方便以后查看
			for (Course course : subjectCourses) {
				limitCourseIds.append(course.getCourseId()).append(",");
				tempPrice += course.getPrice().doubleValue();
			}
			if (tempPrice == 0 || tempPrice < couponCodeDTO.getLimitAmount().doubleValue()) {
				map.put("msg", "优惠券不在使用范围内");//无该项目限制的课程或课程价格不满足优惠券限制
			} else {//返回能优惠的课程金额,具体的打折、减额在页面展示
				map.put("msg", "true");//通过验证标志
				map.put("tempPrice", tempPrice);
				map.put("limitCourseIds", limitCourseIds.toString());
			}
		}
		//优惠券课程限制,必须含有优惠券限制的所有课程
		else if (limitCourses != null && limitCourses.size() > 0) {
			StringBuilder limitCourseIds = new StringBuilder();//记录优惠的课程id字符串，方便以后查看
			boolean flag = false;
			for (Course course : limitCourses) {//是否包含全部限制课程
				limitCourseIds.append(course.getCourseId()).append(",");
				if (courseIds.toString().contains(course.getCourseId() + ",")) {
					flag = true;
				}
				tempPrice += course.getPrice().doubleValue();//限制课程总价格
			}
			if (!flag || tempPrice == 0 || tempPrice < couponCodeDTO.getLimitAmount().doubleValue()) {
				map.put("msg", "优惠券不在使用范围内");//购物车没有优惠限制的全部课程或课程价格不满足优惠券限制
			} else {//返回能优惠的课程金额,具体的打折、减额在页面展示
				map.put("msg", "true");//通过验证标志
				map.put("tempPrice", tempPrice);
				map.put("limitCourseIds", limitCourseIds.toString());
			}
		}
		//所有课程都能用
		else {
			for (Course course : courses) {
				tempPrice += course.getPrice().doubleValue();
			}
			if (tempPrice == 0 || tempPrice < couponCodeDTO.getLimitAmount().doubleValue()) {
				map.put("msg", "优惠券不在使用范围内");//购物车课程价格不满足优惠券限制
			} else {//返回能优惠的课程金额,具体的打折、减额在页面展示
				map.put("msg", "true");//通过验证标志
				map.put("tempPrice", tempPrice);
			}
		}
		return map;
	}

	@Override
	public List<CouponCode> getList(CouponCode couponCode, PageRequest page) {
		return couponCodeMapper.getCouponCodeList(couponCode, page);
	}

	@Override
	public long count(CouponCode couponCode) {
		return couponCodeMapper.countCouponCode(couponCode);
	}

	/*
	 * 个人中心 我的优惠券
	 */
	@Override
	public List<CouponCodeDTO> getDTOList(CouponCodeQuery couponCodeQuery, PageRequest page) {
		return couponCodeMapper.getCouponCodeDTOList(couponCodeQuery, page);
	}

	@Override
	public int countCouponCodeDTO(CouponCodeQuery couponCodeQuery) {
		return couponCodeMapper.countCouponCodeDTO(couponCodeQuery);
	}
}
